$(function () {
	$("#input_file").fileinput({
        language: 'zh',
        showUpload: true,
        showRemove: false,
        showCaption: true,
        previewFileType:'any',
        browseClass: "btn btn-primary",
        allowedFileExtensions : ['pdf'],
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        uploadUrl: 'getInvoiceInfo'
	});
	
	$("#input_file").on("fileuploaded", function (event, data, previewId, index) {
		var fpInfo = data.response;
		$('#fpdm').val(fpInfo.fpdm);
    	$('#fphm').val(fpInfo.fphm);
    	$('#fprq').val(fpInfo.fprq);
    	$('#fpje').val(fpInfo.fpje);
    	getyzmImg(fpInfo.fpdm);
	});
	$("#recognizeBtn").on('click',function(){
		$('.fpInfo .has-error').removeClass('has-error');
		var fpdm = $('#fpdm').val();
		var fphm = $('#fphm').val();
		var fprq = $('#fprq').val();
		var fpje = $('#fpje').val();
		if(!getIp(fpdm)){
			$('#fpdm').parent('div').addClass('has-error');
			Invoice.modal('提示', '请输入正确的发票代码');
			return;
		}
		if(!fphm){
			$('#fphm').parent('div').addClass('has-error');
			Invoice.modal('提示', '请输入正确的发票号码');
			return;
		}
		if(fprq.length != 8){
			$('#fprq').parent('div').addClass('has-error');
			Invoice.modal('提示', '请输入正确的开票日期');
			return;
		}
		if(fpje.length <= 6){
			$('#fpje').parent('div').addClass('has-error');
			Invoice.modal('提示', '发票校验码至少6位');
			return;
		}
		fpje = fpje.substring(fpje.length - 6);
		var validCode = $('#validCode').val();
		if(validCode.length > 0){
			checkInvoice(fpdm, fphm, fprq, fpje, validCode);
		}else{
			$('#validCode').parent('div').addClass('has-error');
			Invoice.modal('提示', '请输入验证码');
		}
	});
	$("#image").click(function() {
	    var fpdm = $("#fpdm").val().trim();
	    if (fpdm == "") {
	    	$('#fpdm').parent('div').addClass('has-error');
	        Invoice.modal('提示', '请先输入发票代码!');
	    } else {
	    	$('.fpInfo .has-error').removeClass('has-error');
	        getyzmImg(fpdm);
	    }
	});
});

var citys = 
	[{'code':'1100','sfmc':'北京','Ip':'https://zjfpcyweb.bjsat.gov.cn:443',
	'address':'https://zjfpcyweb.bjsat.gov.cn:443'},
	 {'code':'1200','sfmc':'天津','Ip':'https://fpcy.tjsat.gov.cn:443',
	 'address':'https://fpcy.tjsat.gov.cn:443'},
	 {'code':'1300','sfmc':'河北','Ip':'https://fpcy.he-n-tax.gov.cn:82',
	 'address':'https://fpcy.he-n-tax.gov.cn:82'},
	 {'code':'1400','sfmc':'山西','Ip':'https://fpcy.tax.sx.cn:443',
	 'address':'https://fpcy.tax.sx.cn:443'},
	 {'code':'1500','sfmc':'内蒙古','Ip':'https://fpcy.nm-n-tax.gov.cn:443',
	 'address':'https://fpcy.nm-n-tax.gov.cn:443'},
	 {'code':'2100','sfmc':'辽宁','Ip':'https://fpcy.tax.ln.cn:443',
	 'address':'https://fpcy.tax.ln.cn:443'},
	 {'code':'2102','sfmc':'大连','Ip':'https://fpcy.dlntax.gov.cn:443',
	 'address':'https://fpcy.dlntax.gov.cn:443'},
	 {'code':'2200','sfmc':'吉林','Ip':'https://fpcy.jl-n-tax.gov.cn:4432',
	 'address':'https://fpcy.jl-n-tax.gov.cn:4432'},
	 {'code':'2300','sfmc':'黑龙江','Ip':'https://fpcy.hl-n-tax.gov.cn:443',
	 'address':'https://fpcy.hl-n-tax.gov.cn:443'},
	 {'code':'3100','sfmc':'上海','Ip':'https://fpcyweb.tax.sh.gov.cn:1001',
	 'address':'https://fpcyweb.tax.sh.gov.cn:1001'},
	 {'code':'3200','sfmc':'江苏','Ip':'https://fpdk.jsgs.gov.cn:80',
	 'address':'https://fpdk.jsgs.gov.cn:80'},
	 {'code':'3300','sfmc':'浙江','Ip':'https://fpcyweb.zjtax.gov.cn:443',
	 'address':'https://fpcyweb.zjtax.gov.cn:443'},
	 {'code':'3302','sfmc':'宁波','Ip':'https://fpcy.nb-n-tax.gov.cn:443',
	 'address':'https://fpcy.nb-n-tax.gov.cn:443'},
	 {'code':'3400','sfmc':'安徽','Ip':'https://fpcy.ah-n-tax.gov.cn:443',
	 'address':'https://fpcy.ah-n-tax.gov.cn:443'},
	 {'code':'3500','sfmc':'福建','Ip':'https://fpcyweb.fj-n-tax.gov.cn:443',
	 'address':'https://fpcyweb.fj-n-tax.gov.cn:443'},
	 {'code':'3502','sfmc':'厦门','Ip':'https://fpcy.xm-n-tax.gov.cn',
	 'address':'https://fpcy.xm-n-tax.gov.cn'},
	 {'code':'3600','sfmc':'江西','Ip':'https://fpcy.jxgs.gov.cn:82',
	 'address':'https://fpcy.jxgs.gov.cn:82'},
	 {'code':'3700','sfmc':'山东','Ip':'https://fpcy.sd-n-tax.gov.cn:443',
	 'address':'https://fpcy.sd-n-tax.gov.cn:443'},
	 {'code':'3702','sfmc':'青岛','Ip':'https://fpcy.qd-n-tax.gov.cn:443',
	 'address':'https://fpcy.qd-n-tax.gov.cn:443'},
	 {'code':'4100','sfmc':'河南','Ip':'https://fpcy.ha-n-tax.gov.cn',
	 'address':'https://fpcy.ha-n-tax.gov.cn'},
	 {'code':'4200','sfmc':'湖北','Ip':'https://fpcy.hb-n-tax.gov.cn:443',
	 'address':'https://fpcy.hb-n-tax.gov.cn:443'},
	 {'code':'4300','sfmc':'湖南','Ip':'https://fpcy.hntax.gov.cn:8083',
	 'address':'https://fpcy.hntax.gov.cn:8083'},
	 {'code':'4400','sfmc':'广东','Ip':'https://fpcy.gd-n-tax.gov.cn:443',
	 'address':'https://fpcy.gd-n-tax.gov.cn:443'},
	 {'code':'4403','sfmc':'深圳','Ip':'https://fpcy.szgs.gov.cn:443',
	 'address':'https://fpcy.szgs.gov.cn:443'},
	 {'code':'4500','sfmc':'广西','Ip':'https://fpcy.gxgs.gov.cn:8200',
	 'address':'https://fpcy.gxgs.gov.cn:8200'},
	 {'code':'4600','sfmc':'海南','Ip':'https://fpcy.hitax.gov.cn:443',
	 'address':'https://fpcy.hitax.gov.cn:443'},
	 {'code':'5000','sfmc':'重庆','Ip':'https://fpcy.cqsw.gov.cn:80',
	 'address':'https://fpcy.cqsw.gov.cn:80'},
	 {'code':'5100','sfmc':'四川','Ip':'https://fpcy.sc-n-tax.gov.cn:443',
	 'address':'https://fpcy.sc-n-tax.gov.cn:443'},
	 {'code':'5200','sfmc':'贵州','Ip':'https://fpcy.gz-n-tax.gov.cn:80',
	 'address':'https://fpcy.gz-n-tax.gov.cn:80'},
	 {'code':'5300','sfmc':'云南','Ip':'https://fpcy.yngs.gov.cn:443',
	 'address':'https://fpcy.yngs.gov.cn:443'},
	 {'code':'5400','sfmc':'西藏','Ip':'https://fpcy.xztax.gov.cn:81',
	 'address':'https://fpcy.xztax.gov.cn:81'},
	 {'code':'6100','sfmc':'陕西','Ip':'https://fpcyweb.sn-n-tax.gov.cn:443',
	 'address':'https://fpcyweb.sn-n-tax.gov.cn:443'},
	 {'code':'6200','sfmc':'甘肃','Ip':'https://fpcy.gs-n-tax.gov.cn:443',
	 'address':'https://fpcy.gs-n-tax.gov.cn:443'},
	 {'code':'6300','sfmc':'青海','Ip':'https://fpcy.qh-n-tax.gov.cn:443',
	 'address':'https://fpcy.qh-n-tax.gov.cn:443'},
	 {'code':'6400','sfmc':'宁夏','Ip':'https://fpcy.nxgs.gov.cn:443',
	 'address':'https://fpcy.nxgs.gov.cn:443'},
	 {'code':'6500','sfmc':'新疆','Ip':'https://fpcy.xj-n-tax.gov.cn:443',
	 'address':'https://fpcy.xj-n-tax.gov.cn:443'}],
	 yzmInfo = {}, Invoice = {}, ip, mainIp = "https://inv-veri.chinatax.gov.cn/";
	 
var getIp = function(fpdm){
	if(fpdm.length < 5){
		return null;
	}
	var dqdm = null;
	if (fpdm.length == 12) {
		dqdm = fpdm.substring(1, 5);
	} else {
		dqdm = fpdm.substring(0, 4);
	}
	if (dqdm != "2102" && dqdm != "3302" && dqdm != "3502" && dqdm != "3702"
			&& dqdm != "4403") {
		dqdm = dqdm.substring(0, 2) + "00";
	}
	for (var i = 0; i < citys.length; i++) {
		if (dqdm == citys[i].code) {
			return ip = citys[i].Ip + "/WebQuery";
		}
	}
	return null;
}
var getyzmImg = function(fpdm) {
	ip = getIp(fpdm);
	if(!ip){
		Invoice.modal('提示', '发票代码错误!');
		return;
	}
	$.ajax({
		type : "post",
		url : ip + "/yzmQuery",
		data : {
			'fpdm' : fpdm,
			'r' : Math.random()
		},
		dataType : "jsonp",
		jsonp : "callback",
		success : function(jsonData) {
			yzmInfo = jsonData;
			var key1 = jsonData.key1;
			if (key1 == "003") {
				Invoice.modal("警告", "验证码请求次数过于频繁，请1分钟后再试");
			} else if (key1 == "005") {
				Invoice.modal("警告", "非法请求");
			} else if (key1 == "010") {
				Invoice.modal("提示", "网络超时，请重试！(01)");
			} else if (key1 == "fpdmerr") {
				Invoice.modal("提示", "请输入合法发票代码");
			} else if (key1 == "024") {
				Invoice.modal("警告", "24小时内验证码请求太频繁，请稍后再试");
			} else if (key1 == "016") {
				Invoice.modal("警告", "服务器接收的请求太频繁，请稍后再试！");
			} else if (key1 == "020") {
				Invoice.modal("警告", "由于查验行为异常，涉嫌违规，当前无法使用查验服务！");
			} else if (key1 != "") {
				$('#image').attr('src', "data:image/png;base64," + key1);
				var texttt;
				if (jsonData.key4 == '00') {
					texttt = "请输入验证码文字";
				} else if (jsonData.key4 == '01') {
					texttt = "请输入验证码图片中<font color=\"red\" size=\"4\" " +
							"style=\"background:#C0C0C0\">红色</font>文字";
				} else if (jsonData.key4 == '02') {
					texttt = "请输入验证码图片中<font color=\"yellow\" size=\"4\" " +
							"style=\"background:#C0C0C0\">黄色</font>文字";
				} else if (jsonData.key4 == '03') {
					texttt = "请输入验证码图片中<font color=\"blue\" size=\"4\" " +
							"style=\"background:#C0C0C0\">蓝色</font>文字";
				}
				$('#imageText').html(texttt);
				$('#recognizeBtn').removeAttr('disabled');
			}
		},
		timeout : 5000,
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			Invoice.modal("警告", "请求错误");
		}
	});
}
var checkInvoice = function(fpdm, fphm, kprq, fpje, yzm) {
	var yzmSj = yzmInfo.key2;
	var swjgmc = "";
	var fplx = "10";
	$.ajax({
		type : "post",
		url : ip + "/query",
		dataType : "jsonp",
		data : {
			'fpdm' : fpdm,
			'fphm' : fphm,// 发票号码
			'kprq' : kprq, // 开票日期
			'fpje' : fpje,// 校验码
			'fplx' : fplx, // fplx
			'yzm' : yzm,// 验证码
			'yzmSj' : yzmSj,// 验证码时间
			'index' : yzmInfo.key3,
			'iv' : CryptoJS.lib.WordArray.random(128 / 8)
					.toString(CryptoJS.enc.Hex),// iv
			'salt' : CryptoJS.lib.WordArray.random(128 / 8)
					.toString(CryptoJS.enc.Hex)
		},
		jsonp : "callback",
		success : function(jsonData) {
			var cyjgdm = jsonData.key1;
			if (cyjgdm == "1") {
				// 标志为1，是试运行且代码为非北京，上海，深圳的。防范前台没卡住的情况
				Invoice.modal("提示", "该省尚未开通发票查验功能！");
			} else if (cyjgdm == "001") {
//				Invoice.modal("验证通过", "该发票是合法的");
				// var t = "var
				// aa17=fpdm+\"≡\"+fphm+\"≡\"+swjgmc+\"≡\"+jsonData.key2+\"≡\"+yzmSj";
				// 这里是从后台传来的
				eval(jsonData.key5);
				var hwxx = jsonData.key3;
				var jmbz = "";
				var aesUtil = new AesUtil(128, 100);
				if (jsonData.key4.trim() != '') {
					jmbz = aesUtil.decrypt(jsonData.key8, jsonData.key7,
							jsonData.key9, jsonData.key4); // 解密备注
				}
				var jmsort = aesUtil.decrypt(jsonData.key8, jsonData.key7,
						jsonData.key9, jsonData.key10); // 解密排序顺序
				// var tt = "var
				// result={\"template\":3,\"c342\":fplx,\"d64b\":aa17," +
				// 		"\"dbd2\":hwxx,\"jmbz\":jmbz,\"sort\":jmsort}";//这个也是后台传的
				eval(jsonData.key6);
				var jsname = jsonData.key11 + ".js"; // 用哪个js，从后台传过来。还需要一个配置页面
				// key7也需要获取，如果未获取到，则用上面定义的jsname，否则，使用key7代入的jsname。
				var browser = getBrowser();
				if (browser == "edge" || browser == "firefox") {
					sessionStorage["jsname"] = jsname;
					$.getScript(mainIp + "js/" + jsname, function() { // 加载,并执行回调函数
																		// (回调函数是空的)
								show_dialog(1100, 700, "cyjgedge" + fplx
												+ ".html", result);
							});
				} else if (browser == "ie8") { // ie8不能通过方法参数获取到相应数据，所以特殊处理
					sessionStorage["jsname"] = jsname;
					sessionStorage["browser"] = "ie8";
					var str = JSON.stringify(result);
					sessionStorage["result"] = str;
					$.getScript(mainIp + "js/" + jsname, function() { // 加载,并执行回调函数
																		// (回调函数是空的)
								show_dialog(1100, 700, "cyjgedge" + fplx
												+ ".html", result);
							});
				} else {
					sessionStorage["jsname"] = jsname;
					$.getScript(mainIp + "js/" + jsname, function() { // 加载,并执行回调函数
								sessionStorage["rule"] = rule;
								window.showModalDialog('cyjg' + fplx
														+ '.html', result,
												"dialogTop:10px;dialogWidth:1100px;dialogHeight:700px;");
							});
				}
			} else if (cyjgdm == "002") {
				Invoice.modal("提示", "超过该张发票当日查验次数(请于次日再次查验)!");
			} else if (cyjgdm == "003") {
				Invoice.modal("提示", "发票查验请求太频繁，请稍后再试！");
			} else if (cyjgdm == "004") {
				Invoice.modal("提示", "超过服务器最大请求数，请稍后访问!");
			} else if (cyjgdm == "005") {
				Invoice.modal("提示", "请求不合法!");
			} else if (cyjgdm == "020") {
				Invoice.modal("提示", "由于查验行为异常，涉嫌违规，当前无法使用查验服务！");
			} else if (cyjgdm == "006") {
//				Invoice.modal("提示", "不一致");
				param = {
					'fplx' : fplx,
					'swjg' : swjgmc,
					'fpdm' : fpdm,
					'fphm' : fphm,
					'kprq' : kprq,
					'kjje' : fpje,
					'cysj' : yzmSj,
					'setText' : "不一致"
				};
				window.showModalDialog('jgbyz.html', param,
								"dialogWidth:700px;dialogHeight:400px;center:yes;scroll:no");
			} else if (cyjgdm == "007") {
				Invoice.modal("提示", "验证码失效!");
			} else if (cyjgdm == "008") {
				Invoice.modal("提示", "验证码错误!");
			} else if (cyjgdm == "009") {
				Invoice.modal("提示", "查无此票");
			} else if (cyjgdm == "rqerr") {
				Invoice.modal("提示", "当日开具发票可于次日进行查验！");
			} else if (cyjgdm == "010") {
				var etype = jsonData.key2;
				Invoice.modal(etype);
				if (etype == 'inredis') {
					etype = "(02)";
				} else if (etype == 'weberr') {
					etype = "(03)";
				}
				Invoice.modal("警告", "网络超时，请重试！" + etype, "系统错误");
			} else if (cyjgdm == "010_") {
				Invoice.modal("警告", "网络超时，请重试！(05)", "系统错误");
			} else {
				Invoice.modal("警告", "网络超时，请重试！(04)", "系统错误");
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			Invoice.modal("警告", "请求错误");
		}
	});
}
Invoice.modal = function(title, text) {
	$('#myModalLabel').html(title);
	$('#modalBody').html(text);
	$('#myModal').modal();
//	$('.modal-footer input').focus();
};